<template>
    <div class="page-container">
        <div class="page-row">
            <el-form :inline="true" :model="queryParam" size="small">
                <el-form-item label-width="标题" prop="title" style="margin-right: 15px;">
                    <el-input style="height: 26px" v-model="queryParam.title" placeholder="请输入标题" :suffix-icon="Search"
                        @keydown.enter.prevent="search"></el-input>
                </el-form-item>
                <el-form-item label="关联文章分类" prop="classId">
                    <el-select v-model="queryParam.classId" clearable placeholder="请关联">
                        <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <el-button type="primary" size="small" @click="search">查询</el-button>
        </div>
        <el-row>
            <el-button type="primary" size="small" @click="addArticle">添加内容</el-button>
        </el-row>
        <div class="table-box">
            <el-table :data="list" size="small" row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="margin-top:10px">
                <el-table-column label="标题" prop="title"></el-table-column>
                <el-table-column label="所属分类" prop="className"></el-table-column>
                <el-table-column label="分类标识" prop="classType"></el-table-column>
                <el-table-column label="状态" prop="status">
                    <template #default="scope">
                        <el-switch size="small" v-model="scope.row.status" :active-value="1" :inactive-value="2"
                            :active-text="scope.row.status == 1 ? '已发布' : '未发布'"
                            @change="changeStatus(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="摘要" prop="articleAbstract"></el-table-column>
                <el-table-column label="数量限制" prop="numRestrict"></el-table-column>
                <el-table-column label="发布时间" prop="createTime"></el-table-column>
                <el-table-column label="操作" width="100px" align="center" fixed="right">
                    <template #default="scope">
                        <!-- <el-button type="primary" link @click="handleShow(scope.row)" size="small">内容</el-button> -->
                        <el-button type="primary" link @click="handleEdit(scope.row)" size="small">编辑</el-button>
                        <el-button type="primary" link @click="delRow(scope.row)" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="page-block">
            <el-pagination v-model:currentPage="queryParam.current" v-model:page-size="queryParam.size"
                :page-sizes="[10, 20, 30, 40]" :small="true" :disabled="false" :background="false"
                layout="total, sizes, prev, pager, next, jumper" :total="total" :hide-on-single-page="false"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <el-drawer v-model="showAddModal" :with-header="true" :title="title" @close="close" :append-to-body="true" size="1220px" ref="drawerRef"
            class="customer-detail-drawer" :modal="true" modal-class="customer-modal">

            <div class="app-container">
                <el-form :model="modalForm" :rules="rules" size="small" label-width="150px" ref="ruleRefForm" class="refForm">
                    <el-form-item label="标题:" prop="title">
                        <el-input v-model="modalForm.title" placeholder="请输入名称"></el-input>
                    </el-form-item>
                    <el-form-item label="关联文章分类" prop="classId">
                        <el-select v-model="modalForm.classId" clearable placeholder="请关联">
                            <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="首图:" prop="image">
                        <el-upload :file-list="modalForm.image" ref="uploadBanner" :action="uploadUrl" :headers="headers"
                            list-type="picture-card" :auto-upload="true" :multiple="false" :limit="1"
                            :on-success="backageImagesOnSuccess">
                            <el-icon>
                                <ele-Camera />
                            </el-icon>
                            <template #file="{ file }">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                        <el-icon>
                                            <ele-ZoomIn />
                                        </el-icon>
                                    </span>
                                    <span class="el-upload-list__item-delete" @click="handleRemove(2, file)">
                                        <el-icon>
                                            <ele-Delete />
                                        </el-icon>
                                    </span>
                                </span>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="摘要:" prop="articleAbstract">
                        <el-input v-model="modalForm.articleAbstract" type="textarea" />
                    </el-form-item>
                    <el-form-item label="状态:" prop="status">
                        <el-radio-group v-model="modalForm.status">
                            <el-radio :label="0">关闭</el-radio>
                            <el-radio :label="1">发布</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="内容">
                        <Editor v-model="modalForm.content" />                    
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" size="small" @click="submitForm(ruleRefForm)">保存</el-button>
                    <el-button size="small" @click="close">取消</el-button>
                </span>
            </template>

            <div class="tabs-list">
                <div class="close-btn" @click="close">
                    <el-icon color="var(--next-color-white)" size="28px">
                        <ele-CircleClose />
                    </el-icon>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, toRefs, onMounted } from 'vue'
import Editor from '/@/components/editor/index.vue'
import { create, update } from  '/@/api/ws/article'
import { remove } from '/@/api/ws/article'
import { Session } from '/@/utils/storage'
import api from '/@/api/commonApi'
export default {
    name: "HomeCardInfo",
    components: {
        Editor
    },
    setup() {
        const state = reactive({
            uploadUrl: '/api/file/filaAttach/upload',
			headers: {
                '17work': Session.get('token')
            },
            list: [], // 列表数据
            modalForm: {}, // 列表数据
            total: 0, // 总条数
            classList: [], // 分类列表
            queryParam: {
                current: 1, // 当前页
                size: 10,   // 页大小
                title: '', // 用户昵称
                classId: null, // 类型
            },
            rules: {
                title: [{
                    required: true,
                    message: '请输入标题',
                    trigger: 'blur'
                }],
                classId: [{
                    required: true,
                    message: '请选择分类',
                    trigger: 'blur'
                }]
            },
            showAddModal: false, // 控制添加内容弹窗
            title: '', // 抽屉头
        })
        onMounted(() => {
            getList()
            getClassList()
        })
        // 获取列表数据
        const getList = () => {
            api.articleList(state.queryParam).then(res => {
                state.list = res.data.records
                state.total = res.data.total
            })
        }
        // 查询
        const search = () => {
            getList()
        }
        // 条数修改
        const handleSizeChange = e => {
            state.queryParam.size = e
            getList()
        }
        // 页码修改
        const handleCurrentChange = e => {
            state.queryParam.current = e
            getList()
        }
        // 获取分类
        const getClassList = () => {
            api.articleClass().then(res => {
                if (res.code == 0) {
                    state.classList = res.data
                }
            })
        }
        // 添加内容
        const addArticle = () => {
            state.modalForm = {}
            state.title = '添加内容'
            state.showAddModal = true
        }
        // 保存内容
        const submitForm = async (formEl) => {
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
                    let data = form.value
                    if (data.backageImage.length > 0) {
                        data.image = data.backageImage[0].url
                    } else {
                        data.image = null
                    }
                    if (data.id != null && data.id != '') {
                        update(data).then(res => {
                            if (res.code == 0) {
                                ElMessage.success("修改成功");
                                context.emit('onDetailSubmit', true)
                            } else {
                                ElMessage.error("修改失败");
                            }
                        })
                    }
                    // 新增
                    else {
                        create(data).then(res => {
                            if (res.code == 0) {
                                ElMessage.success("添加成功");
                                context.emit('onDetailSubmit', true)
                            } else {
                                ElMessage.error("添加失败");
                            }
                        })

                    }
                }
            })

        }
        // 隐藏导航栏
        const close = () => {
            state.modalForm = {}
            state.showAddModal = false
        }
        // 编辑内容
        const handleEdit = (val) => {
            state.title = '编辑内容'
            let images = []
            images.push({
                name: 'images',
                url: val.image
            })
            // state.modalForm = val
            state.modalForm.skuDefaultImg = images
            console.log(state.modalForm);
            state.showAddModal = true
        }
        // 图片上传成功
        const backageImagesOnSuccess = (response, uploadFiles) => {
            let d = []
            d.push({ name: response.data.name, url: response.data.src })
            state.modalForm.backageImage = d
            state.modalForm.image = state.modalForm.backageImage[0].url
        }
        // 删除内容
        const delRow = row => {
            ElMessageBox.confirm(
                '是否确认删除名称为"' + row.name + '"的数据项？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                remove(row.id).then(res => {
                    if (res.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getList()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '删除失败：' + res.message,
                        })
                    }
                })

            }).catch()
        }
        return {
            getList,
            search,
            close,
            handleEdit,
            delRow,
            submitForm,
            addArticle,
            getClassList,
            handleSizeChange,
            handleCurrentChange,
            backageImagesOnSuccess,
            ...toRefs(state)
        }
    }
}
</script>

<style lang="scss">
.page-row {
    display: flex;
    flex-direction: row;
    align-content: center;
}
</style>